﻿//  Copyright (c) 2010 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.IO;
using System.Web.WebPages;

namespace DNA.Mvc.jQuery
{
    public class DialogBuilder : jQueryComponentBuilder<DialogOptions, Dialog, DialogBuilder>
    {
        public DialogBuilder(Dialog component, ViewContext context, IViewDataContainer container) : base(component, context, container) { }

        /// <summary>
        /// Set dialog body content
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public DialogBuilder Body(Func<object, object> value)
        {
            Component.Template.InlineContent = value;
            return this;
        }

        //public DialogBuilder Body(Action<TextWriter> writer)
        //{
        //    Component.Template.InlineContent = new Func<object, object>(obj => {
        //        return new HelperResult(writer);
        //    });
        //    return this;
        //}

        /// <summary>
        /// Set dialog body content
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public DialogBuilder Body(Action value)
        {
            Component.Template.Content = value;
            return this;
        }

        /// <summary>
        /// Load the dialog content from remote.
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public DialogBuilder Load(string url)
        {
            Component.ContentUrl = url;
            return this;
        }

        /// <summary>
        /// Specified the target element that open the dialog
        /// </summary>
        /// <param name="triggerID"></param>
        /// <returns></returns>
        public DialogBuilder OpenWith(string triggerID)
        {
            return this.OpenWith(triggerID, DomEvents.Click);
        }

        /// <summary>
        /// Specified the target element and trigger event that open the dialog
        /// </summary>
        /// <param name="triggerID"></param>
        /// <param name="openEvent"></param>
        /// <returns></returns>
        public DialogBuilder OpenWith(string triggerID, DomEvents openEvent)
        {
            Component.TriggerID = triggerID;
            Component.TriggerEvent = openEvent;
            return this;
        }

        /// <summary>
        /// Specified the buttons of the dialog
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public DialogBuilder Buttons(Action<DialogButtonFactory> value)
        {
            var factory = new DialogButtonFactory(Component.Buttons, Component, this.ViewContext, this.ViewDataContainer);
            value.Invoke(factory);
            return this;
        }

        protected override string jQueryPluginName
        {
            get { return "dialog"; }
        }

        public override void Render()
        {
            _PreRender();
            base.Render();
            _RegisterStartupScripts();
        }

        public override MvcHtmlString GetHtml()
        {
            _PreRender();
            var result=base.GetHtml();
            _RegisterStartupScripts();
            return result;
        }

        private void _RegisterStartupScripts()
        {
            if (!string.IsNullOrEmpty(Component.TriggerID))
            {
                if (string.IsNullOrEmpty(Component.Name))
                    Component.Name = "dialog_" + Guid.NewGuid().ToString().Substring(0, 5);
                string formatID = Component.TriggerID;
                if (!Component.TriggerID.StartsWith("#") && !Component.TriggerID.StartsWith(".") &&
                    !Component.TriggerID.Equals("document") && !Component.TriggerID.StartsWith("body"))
                    formatID = "#" + Component.TriggerID;
                Helper.RegisterStartupScript("$(\"" + formatID + "\").bind(\"" + Component.TriggerEvent.ToString().ToLower() + "\",function(){$(\"#" + Component.Id + "\").dialog(\"open\");});");
            }
        }

        private void _PreRender()
        {
            if (!string.IsNullOrEmpty(Component.ContentUrl))
            {
                string ajaxScript = Helper.GeneratejQueryAjaxScripts(new jQueryAjaxOptions()
                {
                    AutoHandlingError = false,
                    Url = Component.ContentUrl,
                    OnSuccess = jQuerySelector + ".html(data);"
                });
                Options(opts => opts.OnOpen = ajaxScript);
            }

            if (Component.Buttons.Count > 0)
            {
                Options(opts =>
                {
                    if (opts.Buttons == null) opts.Buttons = new OptionBuilder();
                    foreach (var btn in Component.Buttons)
                    {
                        opts.Buttons.AddFunctionOption("\"" + btn.Text + "\"", btn.OnClick);
                    }
                });
            }
        }

    }
}
